<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-goods"></i>
          商城商品
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-input v-model="search" placeholder="商品名称" class="handle-input mr10" width="55"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-lx-add" @click="showBox()">添加商品</el-button>
      </div>
      <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
        <el-table-column prop="name" label="商品名称"></el-table-column>
        <el-table-column prop="gls" label="中奖概率"></el-table-column>
        <el-table-column prop="money" label="单价"></el-table-column>
        <el-table-column prop="classifyPic" label="展示图片">
          <template #default="scope">
            <el-image class="table-td-thumb" :src="joinpic(scope.row.showPic)" fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="pluralName" label="商品分区"></el-table-column>
        <el-table-column prop="status" label="商品状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status == '0'" type="success">已上架</el-tag>
            <el-tag v-else type="danger">已下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center" v-if="username == 'admin'">
          <template #default="scope">
            <el-button type="text" icon="el-icon-lx-attention" class="green" @click="handleCheak(scope.row)">查看</el-button>
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" @click="handleState(scope.row)">{{ scope.row.status == 0 ? '下架' : '上架' }}</el-button>
            <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center" v-if="username == 'order'">
          <template #default="scope">
            <el-button type="text" icon="el-icon-lx-attention" class="green" @click="handleCheak(scope.row)">查看</el-button>
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" @click="handleState(scope.row)">{{ scope.row.status == 0 ? '下架' : '上架' }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex" :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="创建" v-model="showAddUser" width="70%">
      <el-form ref="form" :model="list" label-width="100px" :disabled="isDisabled">
        <el-row>
          <el-col :span="8">
            <el-form-item label="商品名称">
              <el-input v-model="list.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品分区">
              <el-select v-model="list.pluralId" placeholder="请选择" clearable>
                <el-option v-for="item in pluralList" :key="item.id" :label="item.pluralName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单价">
              <el-input v-model="list.money" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规格">
              <el-input v-model="list.standard"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库存">
              <el-input v-model="list.stock"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="商品图片">
              <div class="crop-demo">
                <img v-if="list.showPic" :src="joinpic(list.showPic)" class="pre-img" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <input class="crop-input" type="file" name="image" accept="image/*" @change="setImage" :disabled="isDisabled" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="展示图片">
              <el-upload action="" list-type="picture-card" :http-request="uploadFileMethod" :on-preview="picPreview" multiple :file-list="picList" :on-remove="picRemove" :class="{ hide: hideUploadCard }" ref="picClear">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog v-model="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="详情">
          <Tinymce-editor :disabled="isDisabled" :value="list.contextDetails" @input="(res) => (list.contextDetails = res)"></Tinymce-editor>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddUser = false">取 消</el-button>
          <el-button v-if="isChange == 1" type="primary" @click="append">确 定</el-button>
          <el-button v-else type="primary" @click="edit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { api, upload } from '@/api/index'
import { formatDate } from '@/common/data'
import TinymceEditor from '@/components/tinymce-editor'
import moment from 'moment'
export default {
  inject: ['reload'],
  filters: {
    formatDate(time) {
      time = time * 1000
      let date = new Date(time)
      return formatDate(date, 'yyyy-MM-dd hh:mm')
    },
  },
  components: { TinymceEditor },
  name: 'basetable',
  data() {
    return {
      username: localStorage.getItem('ms_username'),
      query: {
        pageNo: 1,
      },
      search: '',
      tableData: [],
      showAddUser: false,
      pageTotal: 0,
      list: {},
      classSonList: {},
      classSonListTwo: {},
      isChange: '',
      fileList: [],
      picList: [],
      isDisabled: false,
      downList: [],
      dialogVisible: false,
      hideUploadCard: false,
      partitionList: [
        {
          classifyName: '无',
          id: 0,
        },
        {
          classifyName: '体验商家专区',
          id: 1,
        },
        {
          classifyName: '黄金商家专区',
          id: 2,
        },
        {
          classifyName: '钻石商家专区',
          id: 3,
        },
        {
          classifyName: '皇冠商家专区',
          id: 4,
        },
      ],

      pluralList: [],
    }
  },
  created() {
    this.getData()
    this.getPlural()
  },
  mounted() { },
  methods: {
    dateFormat: function (row, column) {
      var date = row[column.property]
      if (date == undefined) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    joinpic(item) {
      return `https://mall.xiyibaomall.com/imgs/${item}`
    },
    //获取盲盒分区
    getPlural() {
      api('/web/blindPlural/g', { limit: 10, offset: 1 }).then((res) => {
        this.pluralList = res.data.rows
      })
    },
    // 获取分类列表
    getData() {
      api('/web/blindCommodity/g', { limit: 10, offset: this.query.pageNo }).then((res) => {
        this.tableData = res.data.rows
        this.pageTotal = res.data.total
      })
    },
    //预览大图
    picPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    //移除图片
    picRemove(file, fileList) {
      this.fileList = []
      for (const i in fileList) {
        this.fileList.push(fileList[i].url)
        if (fileList[i].raw) {
          this.uploadFileMethod(fileList[i].raw)
        }
      }
    },
    //多图上传
    uploadFileMethod(param) {
      let formData = new FormData()
      if (param.file) {
        formData.append('file', param.file)
      } else {
        formData.append('file', param)
      }
      upload(formData).then((res) => {
        this.fileList.push(this.joinpic(res.data[0].fileName))
        console.log(this.fileList)
        this.hideUploadCard = this.fileList.length >= this.isType
      })
    },
    //上传图片
    setImage(file) {
      let imgFile = file.target.files[0]
      let formData = new FormData() //通过formdata上传
      formData.append('file', imgFile)
      upload(formData).then((res) => {
        this.list.showPic = res.data[0].fileName
      })
    },
    //显示编辑框
    showBox() {
      this.showAddUser = true
      this.isChange = 1
      this.isDisabled = false
    },
    // 触发搜索按钮
    handleSearch() {
      this.getData()
    },
    //创建分类
    append() {
      this.list.showDetails1 = this.fileList[0]
      this.list.showDetails2 = this.fileList[1]
      this.list.showDetails3 = this.fileList[2]
      this.list.commodityClassifyLevel2 = 0
      api('/web/blindCommodity/a', this.list).then((res) => {
        if (res.code === 2000) {
          this.$message.success('新增商品成功')
          this.list = {}
          this.reload()
          this.showAddUser = false
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 删除操作
    handleDelete(row) {
      // 二次确认删除
      let data = JSON.parse(JSON.stringify(row))
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning',
      }).then(() => {
        api('/web/blindCommodity/d', {
          id: data.id,
        }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message)
            this.reload()
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },
    //查看操作
    handleCheak(row) {
      this.picList = []
      this.isDisabled = true
      this.showAddUser = true
      this.isChange = 0
      let data = JSON.parse(JSON.stringify(row))
      this.picList.push({ name: '1', url: data.showDetails1 })
      this.picList.push({ name: '2', url: data.showDetails2 })
      this.picList.push({ name: '3', url: data.showDetails3 })
      this.list = data
    },
    // 编辑操作
    handleEdit(row) {
      this.picList = []
      let data = JSON.parse(JSON.stringify(row))
      this.list = data
      this.isDisabled = false
      this.showAddUser = true
      this.isChange = 0
      this.picList.push({ name: '1', url: data.showDetails1 })
      this.picList.push({ name: '2', url: data.showDetails2 })
      this.picList.push({ name: '3', url: data.showDetails3 })
      // console.log(this.picList);
    },
    //修改分类
    edit() {
      if (this.fileList.length == 0) {
        for (const i in this.picList) {
          this.fileList.push(this.picList[i].url)
        }
      }
      // console.log(this.fileList);
      this.list.showDetails1 = this.fileList[0]
      this.list.showDetails2 = this.fileList[1]
      this.list.showDetails3 = this.fileList[2]
      this.list.commodityClassifyLevel2 = 0
      this.showAddUser = false
      api('/web/blindCommodity/u', this.list).then((res) => {
        if (res.code === 2000) {
          this.$message.success('修改商品成功')
          this.list = {}
          this.reload()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    //上下架
    handleState(row) {
      this.$confirm('确定改变状态', '提示', {
        type: 'warning',
      }).then(() => {
        api('/web/blindCommodity/up', {
          id: row.id,
          status: row.status == 0 ? '1' : '0',
        }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message)
            this.reload()
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },

    // 分页导航
    handlePageChange(val) {
      // console.log(val);
      this.query.pageNo = val
      this.getData()
    },
  },
}
</script>
<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.green {
  color: #0ab618;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  height: 60px;
}

.crop-demo {
  display: flex;
  align-items: flex-end;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 148px;
  height: 148px;

  .pre-img {
    width: 146px;
    height: 146px;
    background: #f8f8f8;
    border: 1px solid #eee;
    border-radius: 5px;
    object-fit: cover;
  }

  .crop-input {
    position: absolute;
    width: 148px;
    height: 148px;
    left: 0px;
    top: 0px;
    opacity: 0;
    cursor: pointer;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
}
</style>
